package com.pig4cloud.pig.village.villager.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pig.village.api.dto.VillagerDTO;
import com.pig4cloud.pig.village.api.dto.FamilyLeaderDTO;
import com.pig4cloud.pig.village.api.dto.VillagerSelect;
import com.pig4cloud.pig.village.api.entity.Family;
import com.pig4cloud.pig.village.api.entity.Section;
import com.pig4cloud.pig.village.api.entity.Team;
import com.pig4cloud.pig.village.api.entity.Villager;
import com.pig4cloud.pig.village.api.request.VillagerSearch;
import com.pig4cloud.pig.village.family.service.IFamilyService;
import com.pig4cloud.pig.village.section.service.ISectionService;
import com.pig4cloud.pig.village.team.service.ITeamService;
import com.pig4cloud.pig.village.villager.mapper.VillagerMapper;
import com.pig4cloud.pig.village.villager.service.IVillagerService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Calendar;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author limbray.li
 * @date 2021/6/26
 */
@Service
public class VillagerServiceImpl extends ServiceImpl<VillagerMapper, Villager> implements IVillagerService {
	@Resource
	private IFamilyService familyService;
	@Resource
	private ITeamService teamService;
	@Resource
	private ISectionService sectionService;
	@Resource
	private VillagerMapper villagerMapper;

	@Override
	public List<VillagerSelect> listAllSelect() {
		List<Villager> list = super.list();
		return convert(list);
	}

	@Override
	public List<VillagerSelect> listByFamilyIdSelect(Long familyId) {
		LambdaQueryWrapper<Villager> query = Wrappers.lambdaQuery();
		query.eq(familyId != null, Villager::getFamilyId, familyId);
		List<Villager> list = super.list(query);
		return convert(list);
	}

	private List<VillagerSelect> convert(List<Villager> list) {
		List<VillagerSelect> resultList = list.stream().map(e -> {
			VillagerSelect vo = new VillagerSelect();
			vo.setId(e.getId());
			vo.setFamilyId(e.getFamilyId());
			vo.setName(e.getName());
			return vo;
		}).collect(Collectors.toList());
		return resultList;
	}

	@Override
	public List<VillagerSelect> listByTeamIdSelect(Long teamId) {
		//先找到team对应的户idList
		LambdaQueryWrapper<Family> query = Wrappers.lambdaQuery();
		query.eq(Family::getTeamId, teamId);
		List<Family> families = familyService.list(query);
		List<Long> familyIds = families.stream().map(Family::getId).collect(Collectors.toList());
		//再通过户id找到用户信息
		LambdaQueryWrapper<Villager> queryVillager = Wrappers.lambdaQuery();
		queryVillager.in(CollectionUtils.isNotEmpty(familyIds), Villager::getFamilyId, familyIds);
		List<Villager> list = super.list(queryVillager);
		return convert(list);
	}

	@Override
	public Integer resideTotal() {
		LambdaQueryWrapper<Villager> query = Wrappers.lambdaQuery();
		// TODO Needs to use enum
		query.eq(Villager::getLivingType, 0);
		return super.count(query);
	}

	@Override
	public Integer nonResidentTotal() {
		LambdaQueryWrapper<Villager> query = Wrappers.lambdaQuery();
		// TODO Needs to use enum
		query.eq(Villager::getLivingType, 1);
		return super.count(query);
	}

	@Override
	public Integer lowIncomeTotal() {
		LambdaQueryWrapper<Villager> query = Wrappers.lambdaQuery();
		query.eq(Villager::getHardGroup, 5);
		return super.count(query);
	}

	@Override
	public Integer farmerTotal() {
		LambdaQueryWrapper<Villager> query = Wrappers.lambdaQuery();
		query.eq(Villager::getRegisterType, 0);
		return super.count(query);
	}


	@Override
	public Integer partyTotal() {
		LambdaQueryWrapper<Villager> query = Wrappers.lambdaQuery();
		query.eq(Villager::getPartyMember, 0);
		return super.count(query);
	}

	@Override
	public boolean addOrUpdateVillager(VillagerDTO villagerInfo) {
		// 根据户号查询户id
		LambdaQueryWrapper<Family> queryFamily = Wrappers.lambdaQuery();
		queryFamily.eq(villagerInfo.getFamilyName() != null, Family::getFamilyName, villagerInfo.getFamilyName());
		List<Family> familyList = familyService.list(queryFamily);
		if (familyList != null && familyList.size() != 0) {
			villagerInfo.setFamilyId(familyList.get(0).getId());
		}
		// 判断是否死亡状态
		if (villagerInfo.getDeadDate() != null) {
			villagerInfo.setStatus(0);
		} else {
			villagerInfo.setStatus(1);
		}

		return super.saveOrUpdate(villagerInfo);
	}

	@Override
	public IPage<VillagerDTO> pageBySearch(Page page, VillagerSearch search) {
		//查询村民人员信息
		IPage<Villager> infoPage = getVillagerInfo(page, search);
		List<Villager> infoList = infoPage.getRecords();
		if (CollectionUtils.isEmpty(infoList)) {
			return infoPage.convert(e -> null);
		}
		//组装数据
		IPage<VillagerDTO> resultList = infoPage.convert(e -> {
			VillagerDTO dto = new VillagerDTO();
			// 年龄
			dto.setAge((int) e.getBirthDate().toLocalDate().until(LocalDate.now(), ChronoUnit.YEARS));
			// 根据户id查询户号
			Family family = familyService.getById(e.getFamilyId());
			dto.setFamilyName(family.getFamilyName());
			dto.setFamilyAddress(family.getAddress());
			// 根据队id查询生产队
			Team team = teamService.getById(e.getTeamId());
			dto.setTeamName(team.getTeamName());

			// 根据片区code查询片区名称
			LambdaQueryWrapper<Section> querySection = Wrappers.lambdaQuery();
			querySection.eq(e.getSectionOwner() != null, Section::getSectionCode, e.getSectionOwner());
			List<Section> sections = sectionService.list(querySection);
			if (sections != null && sections.size() != 0) {
				dto.setSectionName(sections.get(0).getSectionName());
			}

			BeanUtil.copyProperties(e, dto);
			return dto;
		});
		return resultList;
	}

	private IPage<Villager> getVillagerInfo(Page page, VillagerSearch search) {

		//先找到户号（familyName）对应的户id
		LambdaQueryWrapper<Family> queryFamily = Wrappers.lambdaQuery();
		queryFamily.eq(search.getFamilyName() != null, Family::getFamilyName, search.getFamilyName());
		List<Family> families = familyService.list(queryFamily);
		List<Long> familyIds = families.stream().map(Family::getId).collect(Collectors.toList());

		LambdaQueryWrapper<Villager> queryVillager = Wrappers.lambdaQuery();
		queryVillager.eq(search.getFamilyName() != null && familyIds != null && familyIds.size() != 0, Villager::getFamilyId, familyIds.get(0));
		queryVillager.eq(search.getVillagerName() != null, Villager::getName, search.getVillagerName());
		queryVillager.eq(search.getPhone() != null, Villager::getPhone, search.getPhone());
		queryVillager.eq(search.getIdentityCard() != null, Villager::getIdentityCard, search.getIdentityCard());

		// 年龄
		LocalDateTime ageFromDate = null;
		LocalDateTime ageToDate = null;
		if(search.getAgeFrom() != null) {
			ageToDate = getBirthday(search.getAgeFrom());
		}
		if(search.getAgeTo() != null) {
			ageFromDate = getBirthday(search.getAgeTo());
		}
		queryVillager.ge(search.getAgeTo() != null, Villager::getBirthDate, ageFromDate);
		queryVillager.le(search.getAgeFrom() != null, Villager::getBirthDate, ageToDate);
		// 属性相关字段条件
		// 党员
		queryVillager.eq(search.getPartyMember() != null, Villager::getPartyMember, search.getPartyMember());
		// 外来家属
		queryVillager.eq(search.getOutsider() != null, Villager::getOutsider, search.getOutsider());
		// 老队长
		queryVillager.eq(search.getRetiredCaptain() != null, Villager::getRetiredCaptain, search.getRetiredCaptain());
		// 老正副职
		queryVillager.eq(search.getRetiredPrincipal() != null, Villager::getRetiredPrincipal, search.getRetiredPrincipal());
		// 居住类型
		queryVillager.eq(search.getLivingType() != null, Villager::getLivingType, search.getLivingType());
		// 户籍性质
		queryVillager.eq(search.getRegisterType() != null, Villager::getRegisterType, search.getRegisterType());
		// 医保属性
		queryVillager.eq(search.getMedicalInsurance() != null, Villager::getMedicalInsurance, search.getMedicalInsurance());
		// 特殊家庭
		queryVillager.eq(search.getSpecialFamily() != null, Villager::getSpecialFamily, search.getSpecialFamily());
		// 拥军拥属
		queryVillager.eq(search.getArmy() != null, Villager::getArmy, search.getArmy());
		// 分管片区
		queryVillager.eq(search.getSectionOwner() != null, Villager::getSectionOwner, search.getSectionOwner());
		// 困难群众
		queryVillager.eq(search.getHardGroup() != null, Villager::getHardGroup, search.getHardGroup());

//		Map attribution = search.getAttribution();
		queryVillager.orderByDesc(Villager::getCreateTime);
		return super.page(page, queryVillager);
	}

	private LocalDateTime getBirthday(int ageYear) {
		Calendar date = Calendar.getInstance();
		Integer year = date.get(Calendar.YEAR);
		LocalDateTime localDateTime = LocalDateTime.of(year - ageYear + 1, 1, 1, 0, 0);
		return localDateTime;
	}

	@Override
	public List<FamilyLeaderDTO> listAllFamilyLeader(){
		return villagerMapper.listAllFamilyLeader();
	}
}
